<template>
  <div class="editor-container">
    <div class="user-avatar">
      <img :src="userAvatar" alt="用户头像" />
    </div>

    <!-- 编辑器主体 -->
    <div class="editor-main">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        mode="default"
      />

      <Editor
        style="height: 85px"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        mode="default"
        @onCreated="handleCreated"
        @onChange="handleChange"
      />
      <!-- 底部操作按钮 -->
      <div class="editor-actions">
        <el-button size="small" @click="handleCancel">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="!content.trim()"
          @click="handleSubmit"
        >
          发表
        </el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onBeforeUnmount, shallowRef } from "vue";
  import { ElButton } from "element-plus";
  import "@wangeditor/editor/dist/css/style.css";
  import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
  import type {
    IDomEditor,
    IEditorConfig,
    IToolbarConfig,
  } from "@wangeditor/editor";

  // 定义组件事件
  const emit = defineEmits<{
    submit: [content: string];
    cancel: [];
  }>();

  // 响应式数据
  const content = ref("");
  const valueHtml = ref("");
  const editorRef = shallowRef<IDomEditor>();
  const userAvatar = ref(
    "https://api.dicebear.com/7.x/avataaars/svg?seed=CurrentUser",
  );

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {
    toolbarKeys: [
      "bold",
      "italic",
      "underline",
      "|",
      "bulletedList",
      "numberedList",
      "|",
      "insertLink",
      "uploadImage",
      "|",
      "blockquote",
      "code",
      // "|",
      // "emotion",
      // "|",
      // "undo",
      // "redo",
    ],
  };

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: "发表评论...",
    MENU_CONF: {
      uploadImage: {
        // 自定义上传
        customUpload(file: File, insertFn: Function) {
          // 将图片转换为base64
          const reader = new FileReader();
          reader.onload = (e) => {
            const base64 = e.target?.result as string;
            // 插入图片到编辑器
            insertFn(base64, file.name, base64);
          };
          reader.readAsDataURL(file);
        },
        // 限制文件大小和类型
        maxFileSize: 5 * 1024 * 1024, // 5M
        allowedFileTypes: ["image/*"],
        // 自定义校验
        customBrowseAndUpload(insertFn: Function) {
          // 创建文件输入元素
          const input = document.createElement("input");
          input.type = "file";
          input.accept = "image/*";
          input.multiple = false;

          input.onchange = (e) => {
            const file = (e.target as HTMLInputElement).files?.[0];
            if (!file) return;

            // 检查文件大小
            if (file.size > 5 * 1024 * 1024) {
              console.error("图片大小不能超过5MB");
              return;
            }

            // 检查文件类型
            if (!file.type.startsWith("image/")) {
              console.error("只能上传图片文件");
              return;
            }

            // 转换为base64
            const reader = new FileReader();
            reader.onload = (e) => {
              const base64 = e.target?.result as string;
              insertFn(base64, file.name, base64);
            };
            reader.readAsDataURL(file);
          };

          input.click();
        },
      },
    },
  };

  // 编辑器创建完毕时的回调函数
  const handleCreated = (editor: IDomEditor) => {
    editorRef.value = editor;
  };

  // 编辑器内容改变时的回调函数
  const handleChange = (editor: IDomEditor) => {
    content.value = editor.getText();
  };

  // 提交评论
  const handleSubmit = () => {
    if (content.value.trim()) {
      emit("submit", valueHtml.value);
      // 清空编辑器
      if (editorRef.value) {
        editorRef.value.clear();
        valueHtml.value = "";
        content.value = "";
      }
    }
  };

  // 取消评论
  const handleCancel = () => {
    emit("cancel");
    // 清空编辑器
    if (editorRef.value) {
      editorRef.value.clear();
      valueHtml.value = "";
      content.value = "";
    }
  };

  // 聚焦编辑器
  const focusEditor = () => {
    if (editorRef.value) {
      editorRef.value.focus();
    }
  };

  // 组件销毁时，销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
  });

  // 暴露方法给父组件
  defineExpose({
    focusEditor,
  });
</script>

<style lang="scss" scoped>
  .editor-container {
    display: flex;
    .user-avatar {
      img {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        object-fit: cover;
      }
    }

    .editor-main {
      flex: 1;
      border: 1px solid #e1e5e9;
      border-radius: 8px;
      overflow: hidden;
      height: 160px;

      .editor-actions {
        display: flex;
        justify-content: flex-end;
        border-top: 1px solid #e1e5e9;
        padding: 5px;
        background-color: white;
      }
    }
  }
</style>
